<script setup>
import MdiPlusIcon from '@/components/icons/MdiPlusIcon.vue'
import { Delete, Edit, Grid, InfoFilled, UploadFilled } from '@element-plus/icons-vue'
import { reactive, ref, watchEffect } from 'vue'
import { addNewCarousel, queryCarouselList, deleteCarousel, updateCarousel } from '@/service/carousel'
import { upload } from '@/service/file.js'
import { querySimpleProductInfo } from '@/service/product.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const carouselList = ref([])

async function loadCarouselList() {
  const res = await queryCarouselList()
  carouselList.value = res.data
}
let carouselForm = reactive({
  id: null,
  imageUrl: null,
  productId: null,
  sort: '',
  status: 1,
  title: '',
})
const rules = reactive({
  imageUrl: [{ required: true, message: '', trigger: 'blur' }],
  productId: [{ required: true, message: '', trigger: 'blur' }],
})
const showAddCarouselDialog = ref(false)
watchEffect(() => {
  if (showAddCarouselDialog.value === false || showEditCarouselDialog.value === false) {
    Object.assign(carouselForm, {
      id: null,
      imageUrl: '',
      productId: '',
      sort: 1,
      status: 1,
      title: '',
    })
  }
})
function onTapAddCarouselButton() {
  showAddCarouselDialog.value = true
}
const carouselFormRef = ref()
function onTapSaveButton() {
  carouselFormRef.value.validate(async (valid, invalidFields) => {
    if (valid) {
      const params = {}
      params.type = 1
      params.title = carouselForm.title
      params.carouselImage = carouselForm.imageUrl
      params.status = carouselForm.status
      params.sort = carouselForm.sort
      params.productId = carouselForm.productId
      await addNewCarousel(params)
      ElMessage.success('成功添加轮播图！')
      await loadCarouselList()
      showAddCarouselDialog.value = false
    } else {
      if ('imageUrl' in invalidFields) {
        ElMessage.error('轮播图不能为空！')
      } else if ('productId' in invalidFields) {
        ElMessage.error('关联商品不能为空！')
      }
    }
  })
}
loadCarouselList()
const fileInput = ref()
function openFileSelector() {
  fileInput.value.click()
}
async function handleFileSelect(event) {
  const selectedFile = event.target.files[0]
  const res = await upload(selectedFile)
  carouselForm.imageUrl = res.data
}
const loadingRemoteData = ref(false)
const productInfoList = ref([])
async function loadRemoteProductInfo(query) {
  loadingRemoteData.value = true
  if (query) {
    const res = await querySimpleProductInfo(query)
    productInfoList.value = res.data
  } else {
    productInfoList.value = []
  }
  loadingRemoteData.value = false
}
async function onTapDeleteButton(item) {
  console.log(item)
  ElMessageBox.confirm('确定要删除这个预览图吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await deleteCarousel(item.id)
      await loadCarouselList()
      ElMessage({
        type: 'success',
        message: '成功删除',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const showEditCarouselDialog = ref(false)
async function onTapEditCarouselButton(item) {
  await loadRemoteProductInfo(item.productId)
  carouselForm.imageUrl = item.carouselImage
  carouselForm.status = item.status
  carouselForm.title = item.title
  carouselForm.sort = item.sort
  carouselForm.id = item.id
  carouselForm.productId = item.productId
  showEditCarouselDialog.value = true
}
async function onTapUpdateButton() {
  carouselFormRef.value.validate(async (valid, invalidFields) => {
    if (valid) {
      const params = {}
      params.type = 1
      params.id = carouselForm.id
      params.title = carouselForm.title
      params.carouselImage = carouselForm.imageUrl
      params.status = carouselForm.status
      params.sort = carouselForm.sort
      params.productId = carouselForm.productId
      await updateCarousel(params)
      ElMessage.success('成功修改轮播图！')
      await loadCarouselList()
      showEditCarouselDialog.value = false
    } else {
      if ('imageUrl' in invalidFields) {
        ElMessage.error('轮播图不能为空！')
      } else if ('productId' in invalidFields) {
        ElMessage.error('关联商品不能为空！')
      }
    }
  })
}
</script>

<template>
  <div class="carousel-management">
    <h2>首页轮播图管理</h2>
    <p style="color: #737373; line-height: 30px">管理小程序首页轮播展示的图片，支持添加、编辑、删除和排序</p>
    <div class="control-panel">
      <div class="add-button">
        <el-button size="large" type="primary" @click="onTapAddCarouselButton">
          <el-icon size="25"><MdiPlusIcon /></el-icon><span>添加轮播图</span>
        </el-button>
        <div class="control-panel-tip">
          <el-icon style="margin-top: 2px; margin-right: 3px"><InfoFilled /></el-icon>
          建议最多添加8张轮播图，建议尺寸：700px × 240px
        </div>
      </div>
      <div class="carousel-review">
        <div class="carousel-review-title">
          <img alt="" src="@/assets/eye.svg" style="width: 18px; height: 18px" />
          <h3>轮播图预览</h3>
        </div>
        <el-carousel arrow="never" class="carousel-review-content">
          <el-carousel-item v-for="item in carouselList.filter((carousel) => carousel.status === 1)" :key="item.id">
            <img :src="item.carouselImage" alt="" />
          </el-carousel-item>
        </el-carousel>
      </div>
      <div class="carousel-list">
        <div class="carousel-list-title">
          <el-icon color="#409EFF" style="margin-right: 7px; margin-top: 2px"><Grid /></el-icon>
          <h3>轮播图列表</h3>
        </div>
        <div class="carousel-list-content">
          <div v-for="(item, index) in carouselList" :key="item.id" class="carousel-item">
            <div class="carousel-sort">{{ index + 1 }}</div>
            <img :src="item.carouselImage" alt="" />
            <div class="carousel-item-info">
              <div class="carousel-title">
                <template v-if="item.title">
                  <span>{{ item.title }}</span>
                </template>
                <template v-else>
                  <span>无标题</span>
                </template>
                <el-tag v-if="item.status === 1" type="success">已启用</el-tag>
                <el-tag v-else type="danger">已禁用</el-tag>
              </div>
              <div class="relation-product">关联商品： {{ item.productName }}</div>
              <div class="carousel-item-bottom-info">
                <div class="product-info-id">商品ID： {{ item.productId }}</div>
                <el-button
                  :icon="Edit"
                  @click="onTapEditCarouselButton(item)"
                  circle
                  style="margin-left: auto"
                  type="default"
                />
                <el-button :icon="Delete" @click="onTapDeleteButton(item)" circle type="danger" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="showAddCarouselDialog" draggable title="添加轮播图">
    <el-divider style="margin: 0; margin-bottom: 10px" />
    <el-form ref="carouselFormRef" :model="carouselForm" :rules="rules" label-position="top">
      <el-form-item label="轮播图片:" prop="imageUrl">
        <div class="upload-container" @click="openFileSelector">
          <div v-if="!carouselForm.imageUrl" class="text">
            <el-icon size="32"><upload-filled /></el-icon>
            <div style="font-size: 14px; color: #737373">点击上传图片</div>
            <div style="font-size: 12px; color: #a3a3a3">支持JPG、PNG格式，建议尺寸720×240px</div>
          </div>
          <img v-else :src="carouselForm.imageUrl" alt="" class="image" />
          <input
            ref="fileInput"
            :multiple="false"
            accept="image/jpeg, image/png"
            style="display: none"
            type="file"
            @change="handleFileSelect"
          />
        </div>
      </el-form-item>
      <el-form-item label="关联商品:" prop="productId">
        <el-select
          v-model="carouselForm.productId"
          :loading="loadingRemoteData"
          :remote-method="loadRemoteProductInfo"
          filterable
          placeholder="请输入商品名称或商品ID"
          remote
        >
          <el-option v-for="item in productInfoList" :key="item.id" :label="item.productName" :value="item.id">
            <div class="product-info">
              <div class="product-id">ID: {{ item.id }}</div>
              <div class="product-name">{{ item.productName }}</div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片描述:">
        <el-input v-model="carouselForm.title" placeholder="图片的描述信息(可选)" />
      </el-form-item>
      <el-form-item label="状态:">
        <el-radio-group v-model="carouselForm.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权重:">
        <el-input-number v-model="carouselForm.sort" :controls="false" :max="1000000" :min="1" :precision="0" />
      </el-form-item>
      <span class="weight-tip">权重越高，则轮播图的位置越靠前</span>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showAddCarouselDialog = false">取消</el-button>
        <el-button type="primary" @click="onTapSaveButton"> 添加 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="showEditCarouselDialog" draggable title="编辑轮播图">
    <el-divider style="margin: 0; margin-bottom: 10px" />
    <el-form ref="carouselFormRef" :model="carouselForm" :rules="rules" label-position="top">
      <el-form-item label="轮播图片:" prop="imageUrl">
        <div class="upload-container" @click="openFileSelector">
          <div v-if="!carouselForm.imageUrl" class="text">
            <el-icon size="32"><upload-filled /></el-icon>
            <div style="font-size: 14px; color: #737373">点击上传图片</div>
            <div style="font-size: 12px; color: #a3a3a3">支持JPG、PNG格式，建议尺寸720×240px</div>
          </div>
          <img v-else :src="carouselForm.imageUrl" alt="" class="image" />
          <input
            ref="fileInput"
            :multiple="false"
            accept="image/jpeg, image/png"
            style="display: none"
            type="file"
            @change="handleFileSelect"
          />
        </div>
      </el-form-item>
      <el-form-item label="关联商品:" prop="productId">
        <el-select
          v-model="carouselForm.productId"
          :loading="loadingRemoteData"
          :remote-method="loadRemoteProductInfo"
          filterable
          placeholder="请输入商品名称或ID"
          remote
        >
          <el-option v-for="item in productInfoList" :key="item.id" :label="item.productName" :value="item.id">
            <div class="product-info">
              <div class="product-id">ID: {{ item.id }}</div>
              <div class="product-name">{{ item.productName }}</div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片描述:">
        <el-input v-model="carouselForm.title" placeholder="图片的描述信息(可选)" />
      </el-form-item>
      <el-form-item label="状态:">
        <el-radio-group v-model="carouselForm.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权重:">
        <el-input-number v-model="carouselForm.sort" :controls="false" :max="1000000" :min="1" :precision="0" />
      </el-form-item>
      <span class="weight-tip">权重越高，则轮播图的位置越靠前</span>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showEditCarouselDialog = false">取消</el-button>
        <el-button type="primary" @click="onTapUpdateButton"> 更新 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.carousel-management {
  width: 100%;
}

.control-panel {
  background-color: #fff;
  padding: 24px;
  margin-top: 20px;
  border-radius: 10px;
}

.control-panel-tip {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #737373;
}

.add-button {
  display: flex;
  justify-content: space-between;
  span {
    font-size: 16px;
  }
}

.carousel-review-title {
  display: flex;
  align-items: center;
  margin-top: 20px;
  img {
    margin-right: 6px;
  }
}

.carousel-list-title {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.carousel-review-content {
  width: 700px;
  height: 240px;
  margin: 0 auto;
  border-radius: 10px;
}

.upload-container {
  padding: 16px;
  width: 300px;
  border: 2px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  margin: 0 auto;
  &:hover {
    border: 2px dashed #409eff;
  }
  .text {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .image {
    width: 100%;
    border-radius: 10px;
  }
}

.product-info {
  display: flex;
  .product-name {
    margin-left: 20px;
  }
}

.carousel-list-content {
  margin-top: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  justify-items: center;
  row-gap: 20px;
  .carousel-item {
    border-radius: 10px;
    border: 1px solid #d9d9d9;
    overflow: hidden;
    width: 300px;
    position: relative;
    .carousel-sort {
      position: absolute;
      top: 5px;
      left: 5px;
      background-color: #ffffffcc;
      color: #404040;
      border-radius: 999px;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      line-height: 20px;
    }
    img {
      width: 100%;
    }
    .carousel-item-info {
      padding: 16px;
      .carousel-title {
        font-size: 16px;
        color: #262626;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        span {
          width: 150px;
        }
      }
      .relation-product {
        font-size: 12px;
        color: #1677ff;
        margin-bottom: 10px;
      }
      .carousel-item-bottom-info {
        display: flex;
        align-items: center;
        .product-info-id {
          font-size: 12px;
          color: #a3a3a3;
        }
      }
    }
  }
}

.weight-tip {
}
</style>
